package com.itwc.websocketdemo.controller;

import com.itwc.websocketdemo.entity.AiPost;
import com.itwc.websocketdemo.entity.UserPostRelation;
import com.itwc.websocketdemo.service.PostService;
import com.itwc.websocketdemo.service.WebSocketService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 推文控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/posts")
public class PostController {

    @Autowired
    private PostService postService;
    
    @Autowired
    private WebSocketService webSocketService;
    
    /**
     * 发布推文（管理员功能）
     */
    @PostMapping("/publish")
    public ResponseEntity<Map<String, Object>> publishPost(@RequestBody AiPost post) {
        Map<String, Object> result = new HashMap<>();
        try {
            AiPost publishedPost = postService.publishPost(post);
            result.put("success", true);
            result.put("message", "推文发布成功");
            result.put("data", publishedPost);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("发布推文失败", e);
            result.put("success", false);
            result.put("message", "发布推文失败：" + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }
    
    /**
     * 获取所有推文
     */
    @GetMapping("/list")
    public ResponseEntity<Map<String, Object>> getAllPosts() {
        Map<String, Object> result = new HashMap<>();
        try {
            List<AiPost> posts = postService.getAllPosts();
            result.put("success", true);
            result.put("data", posts);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("获取推文列表失败", e);
            result.put("success", false);
            result.put("message", "获取推文列表失败：" + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }
    
    /**
     * 获取用户的推文列表（包含未读状态）
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<Map<String, Object>> getUserPosts(@PathVariable Long userId) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<UserPostRelation> posts = postService.getUserPostsWithReadStatus(userId);
            int unreadCount = postService.getUnreadCount(userId);
            
            result.put("success", true);
            result.put("data", posts);
            result.put("unreadCount", unreadCount);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("获取用户推文列表失败", e);
            result.put("success", false);
            result.put("message", "获取用户推文列表失败：" + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }
    
    /**
     * 获取推文详情
     */
    @GetMapping("/{postId}")
    public ResponseEntity<Map<String, Object>> getPostDetail(@PathVariable Long postId) {
        Map<String, Object> result = new HashMap<>();
        try {
            AiPost post = postService.getPostById(postId);
            if (post == null) {
                result.put("success", false);
                result.put("message", "推文不存在");
                return ResponseEntity.status(404).body(result);
            }
            
            result.put("success", true);
            result.put("data", post);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("获取推文详情失败", e);
            result.put("success", false);
            result.put("message", "获取推文详情失败：" + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }
    
    /**
     * 标记推文为已读
     */
    @PostMapping("/{postId}/read")
    public ResponseEntity<Map<String, Object>> markAsRead(@PathVariable Long postId, @RequestParam Long userId) {
        Map<String, Object> result = new HashMap<>();
        try {
            postService.markPostAsRead(userId, postId);
            int unreadCount = postService.getUnreadCount(userId);
            
            result.put("success", true);
            result.put("message", "标记为已读成功");
            result.put("unreadCount", unreadCount);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("标记推文为已读失败", e);
            result.put("success", false);
            result.put("message", "标记为已读失败：" + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }
    
    /**
     * 获取用户未读数量
     */
    @GetMapping("/unread-count/{userId}")
    public ResponseEntity<Map<String, Object>> getUnreadCount(@PathVariable Long userId) {
        Map<String, Object> result = new HashMap<>();
        try {
            int unreadCount = postService.getUnreadCount(userId);
            result.put("success", true);
            result.put("unreadCount", unreadCount);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("获取未读数量失败", e);
            result.put("success", false);
            result.put("message", "获取未读数量失败：" + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }
    
    /**
     * 获取在线用户列表（调试用）
     */
    @GetMapping("/admin/online-users")
    public ResponseEntity<Map<String, Object>> getOnlineUsers() {
        Map<String, Object> result = new HashMap<>();
        try {
            Set<Long> onlineUserIds = webSocketService.getOnlineUserIds();
            result.put("success", true);
            result.put("onlineUsers", onlineUserIds);
            result.put("count", onlineUserIds.size());
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("获取在线用户失败", e);
            result.put("success", false);
            result.put("message", "获取在线用户失败：" + e.getMessage());
            return ResponseEntity.status(500).body(result);
        }
    }
}